package org.jeecg.modules.sggg.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.config.StaticConfig;
import org.jeecg.modules.sggg.entity.*;
import org.jeecg.modules.sggg.service.*;
import org.jeecg.modules.system.controller.SysRoleController;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.wechatSendMessage.TemplateData;
import org.jeecg.modules.wechatSendMessage.WxMssVo;
import org.jeecg.modules.wechatSendMessage.subscribeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 项目表
 * @Author: jeecg-boot
 * @Date: 2023-03-30
 * @Version: V1.0
 */
@Api(tags = "项目表")
@RestController
@RequestMapping("/item/sgItem")
@Slf4j
public class SgItemController extends JeecgController<SgItem, ISgItemService> {
    @Autowired
    private ISgItemService sgItemService;

    @Autowired
    private ISgTaskService taskService;

    @Autowired
    private ISgOperationRecordsService operationRecordsService;

    @Autowired
    private ISgMemberService sgMemberService;

    @Autowired
    private subscribeMessage subscribeMessage;

    @Autowired
    private SysRoleController sysRoleController;

    @Autowired
    private ISgItemTypeService sgItemTypeService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysDepartService sysDepartController;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 分页列表查询
     *
     * @param sgItem
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "项目表-分页列表查询", notes = "项目表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<SgItem>> queryPageList(SgItem sgItem,
                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                               HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<SgItem> queryWrapper = QueryGenerator.initQueryWrapper(sgItem, req.getParameterMap());
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        // 根据DeptAttr机构属性判断当前登录人属于哪个机构（三高之家、三高基地、三高中心）
        if(sysDepart !=null && sysDepart.getDeptAttr()!=null){
            SysUser sysUser1 = sysUserService.getById(sysUser.getId());
            // 1.三高之家
            if(sysDepart.getDeptAttr().equals("1")){
                queryWrapper.eq("sys_org_code", sysUser.getOrgCode().toString());
            }
            // 2.三高基地
            if(sysDepart.getDeptAttr().equals("2")){
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if(sysDepart.getDeptAttr().equals("3")){
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
        }else if(roleCode.contains("dept_manage") || roleCode.contains("admin")){
            queryWrapper.like("sys_org_code",sysUser.getOrgCode());

        }else{
            queryWrapper.eq("sys_org_code", sysUser.getOrgCode().toString());
        }

        Page<SgItem> page = new Page<>(pageNo, pageSize);
        IPage<SgItem> pageList = sgItemService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @GetMapping("/queryList")
    public Result<List<SgItem>> queryList(String mid) {
        SgMember sgMember = sgMemberService.getById(mid);
        List<SgItem> list = sgItemService.list(new QueryWrapper<SgItem>().eq("is_on_sale", 1).eq("sys_org_code", sgMember.getSysOrgCode()));
        list.forEach(item -> {
            long count = 0L;

            QueryWrapper<SgTask> queryWrapper = new QueryWrapper<>();
            QueryWrapper<SgTask> query = new QueryWrapper<>();
            queryWrapper.eq("item_id", item.getId())
                    .eq("member_id", mid).eq("status", 1);

            query.eq("item_id", item.getId())
                    .eq("member_id", mid).eq("status", 0);

            if (item.getCycle() == 0) {//每天刷新
                query.last("and TO_DAYS(create_time) = TO_DAYS(NOW())");
                count = taskService.count(queryWrapper.last("and TO_DAYS(create_time) = TO_DAYS(NOW())"));
            } else if (item.getCycle() == 1) {//每周刷新
                query.last("and YEARWEEK(date_format(create_time,'%Y-%m-%d')) = YEARWEEK(NOW())");
                count = taskService.count(queryWrapper.last("and YEARWEEK(date_format(create_time,'%Y-%m-%d')) = YEARWEEK(NOW())"));
            } else if (item.getCycle() == 2) {//每月刷新
                query.last("and DATE_FORMAT(create_time,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m')");
                count = taskService.count(queryWrapper.last("and DATE_FORMAT(create_time,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m')"));
            } else if (item.getCycle() == 3) {//每年刷新
                query.last("and YEAR(create_time)=YEAR(NOW())");
                count = taskService.count(queryWrapper.last("and YEAR(create_time)=YEAR(NOW())"));
            } else if (item.getCycle() == 4) {//每人仅限一次
                count = taskService.count(queryWrapper);
            } else if (item.getCycle() == 5) {//每次刷新
                count = 0;
            }
            item.setCount(count);
            long statusCount = taskService.count(query);
            if (statusCount == 0) {
                item.setType(0); //去完成,已完成
            } else {
                item.setType(1);
            }

        });
        return Result.OK(list);
    }

    /**
     * pc端使用，用来通过申请的任务列表
     *
     * @return 未通过申请的任务列表
     */
    @GetMapping("/queryTaskList")
    public Result<List<SgTask>> queryTaskList() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysRole> role = sysRoleController.getUserRole(sysUser.getId()).getResult();
        if (role.get(0).getRoleCode().equals("admin")) {
            List<SgTask> list = taskService.queryTaskList(null, sysUser.getOrgCode());
            return Result.OK(list);
        } else if (!role.get(0).getRoleCode().equals("dept_manage") || !role.get(0).getRoleCode().equals("admin")) {
            SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
            SysUser sysUser1 = sysUserService.getById(sysUser.getId());
            List<String> responsibleAgencies = new ArrayList<>();
            // 根据DeptAttr机构属性判断当前登录人属于哪个机构（三高之家、三高基地、三高中心）
            if(sysDepart !=null && sysDepart.getDeptAttr()!=null){

                // 1.三高之家
                if(sysDepart.getDeptAttr().equals("1")){
                    sysUser1.setOrgCode(sysUser.getOrgCode());
//                    queryWrapper.eq("sys_org_code", sysUser.getOrgCode().toString());
                }
                // 2.三高基地
                if(sysDepart.getDeptAttr().equals("2")){
                    String[] array = sysUser1.getResponsibleAgency().split(",");
                     responsibleAgencies = Arrays.asList(array);
//                    sysUser1.setResponsibleAgency(responsibleAgencies);
//                    queryWrapper.in("sys_org_code", responsibleAgencies);
                }
                // 3.三高中心
                if(sysDepart.getDeptAttr().equals("3")){
                    String[] array = sysUser1.getResponsibleAgency().split(",");
                    responsibleAgencies = Arrays.asList(array);
//                    queryWrapper.in("sys_org_code", responsibleAgencies);
                }
            }else if(role.contains("dept_manage") || role.contains("admin")){
                sysUser1.setOrgCode(sysUser.getOrgCode());

            }else{
                sysUser1.setOrgCode(sysUser.getOrgCode());
            }
            List<SgTask> list = taskService.queryTaskListTo(sysUser1.getOrgCode(), responsibleAgencies);
            return Result.OK(list);
        }
//        else if (!role.get(0).getRoleCode().equals("admin") && !role.get(0).getRoleCode().equals("yisheng")) {
//            List<SgTask> list = taskService.queryTaskList(null, sysUser.getOrgCode());
//            return Result.OK(list);
//        }
        return Result.error("操作失败");
    }

    /**
     * 审核任务是否通过
     *
     * @param task 任务对象
     * @return 结果
     */
    @PostMapping("/updateTaskStatus")
    public Result<Boolean> updateTaskStatus(@RequestBody SgTask task) {
        taskService.updateById(task);

        SgTask t = taskService.getById(task.getId());
        //判断是否要加币
        if (task.getStatus() == 1) {
            SgItem item = sgItemService.getById(t.getItemId());
            long count = 0L;
            QueryWrapper<SgTask> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("item_id", task.getItemId())
                    .eq("member_id", task.getMemberId());

            if (item.getCycle() == 0) {//每天刷新
                count = taskService.count(queryWrapper.last("and TO_DAYS(create_time) = TO_DAYS(NOW())"));
            } else if (item.getCycle() == 1) {//每周刷新
                count = taskService.count(queryWrapper.last("and YEARWEEK(date_format(create_time,'%Y-%m-%d')) = YEARWEEK(NOW())"));
            } else if (item.getCycle() == 2) {//每月刷新
                count = taskService.count(queryWrapper.last("and DATE_FORMAT(create_time,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m')"));
            } else if (item.getCycle() == 3) {//每年刷新
                count = taskService.count(queryWrapper.last("and YEAR(create_time)=YEAR(NOW())"));
            } else if (item.getCycle() == 4) {//每人仅限一次
                count = taskService.count(queryWrapper);
            } else if (item.getCycle() == 5) {//每次刷新
                count = item.getPeriod();
            }

            if (item.getName().equals("附加任务")) {
                item.setCurrency(task.getCurrency());
            }

            if (item.getPeriod() == count) {
                //添加获取积分记录
                SgOperationRecords records = new SgOperationRecords();
                records.setType(0);
                records.setMemberId(task.getMemberId());
                records.setTaskId(item.getId());
                records.setNumber(item.getCurrency());
                operationRecordsService.save(records);
                //修改分数
                sgMemberService.updateCurrencyById(task.getMemberId(), item.getCurrency());
            }
        }
        if (task.getStatus() == 2) {//推送一次订阅消息
            SgMember member = sgMemberService.getById(t.getMemberId());
            if (member.getOpenId() != null) {
                StaticConfig staticConfig = SpringContextUtils.getBean(StaticConfig.class);
                WxMssVo wxMssVo = new WxMssVo();
                wxMssVo.setTouser(member.getOpenId());
                wxMssVo.setTemplate_id(staticConfig.getAUDIT_RESULT_NOTICE());
                Map<String, TemplateData> m = new HashMap<>(6);
                m.put("phrase1", new TemplateData("失败"));
                m.put("date4", new TemplateData(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(t.getCreateTime())));
                m.put("thing5", new TemplateData(t.getRemark()));
                String name = sgItemService.getById(t.getItemId()).getName();
                if (name.length() >= 20) {
                    name = name.substring(0, 17) + "...";
                }
                m.put("thing20", new TemplateData(name));
                wxMssVo.setData(m);
                subscribeMessage.send(wxMssVo);
            }
        }
        return Result.OK();
    }

    /**
     * 添加
     *
     * @param sgItem
     * @return
     */
    @AutoLog(value = "项目表-添加")
    @ApiOperation(value = "项目表-添加", notes = "项目表-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody SgItem sgItem) {
        sgItem.setIsOnSale(1);
        sgItemService.save(sgItem);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param sgItem
     * @return
     */
    @AutoLog(value = "项目表-编辑")
    @ApiOperation(value = "项目表-编辑", notes = "项目表-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody SgItem sgItem) {
        sgItemService.updateById(sgItem);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "项目表-通过id删除")
    @ApiOperation(value = "项目表-通过id删除", notes = "项目表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        SgItem sgItem = new SgItem();
        sgItem.setId(id);
        sgItem.setIsOnSale(0);
        sgItemService.updateById(sgItem);
        return Result.OK("下架成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "项目表-批量删除")
    @ApiOperation(value = "项目表-批量删除", notes = "项目表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.sgItemService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "项目表-通过id查询", notes = "项目表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SgItem> queryById(@RequestParam(name = "id", required = true) String id) {
        SgItem sgItem = sgItemService.getById(id);
        if (sgItem == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgItem);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sgItem
     */
    //@RequiresPermissions("item:sg_item:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SgItem sgItem) {
        return super.exportXls(request, sgItem, SgItem.class, "项目表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("item:sg_item:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SgItem.class);
    }


    /**
     * TODO     项目上下架
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/31 9:10
     * @Exception
     */
    @AutoLog(value = "项目表-商品上下架")
    @ApiOperation(value = "项目表-商品上下架", notes = "项目表-商品上下架")
    @RequestMapping(value = "/isOnSale", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> isOnSale(@RequestBody SgItem sgItem) {
        sgItem.setIsOnSale(sgItem.getIsOnSale() == 0 ? 1 : 0);
        sgItemService.updateById(sgItem);
        return Result.OK(sgItem.getIsOnSale() == 0 ? "下架成功!" : "上架成功!");
    }

    /**
     * 撤销任务
     *
     * @param task
     * @return
     */
    @GetMapping("/revokeTask")
    public Result<String> revokeTask(SgTask task) {
        if (task.getType().equals("0")) {
            taskService.remove(new QueryWrapper<SgTask>().eq("item_id", task.getItemId()).eq("member_id", task.getMemberId()).last("LIMIT 1"));
        } else {
            taskService.remove(new QueryWrapper<SgTask>().eq("item_id", task.getItemId()).eq("member_id", task.getMemberId()));
            SgMember member = sgMemberService.getById(task.getMemberId());
            member.setCurrency(member.getCurrency() - task.getCurrency());
            sgMemberService.updateById(member);
            SgOperationRecords sgOperationRecords = new SgOperationRecords();
            sgOperationRecords.setMemberId(task.getMemberId());
            sgOperationRecords.setTaskId(task.getItemId());
            sgOperationRecords.setType(2);
            sgOperationRecords.setNumber(task.getCurrency());
            operationRecordsService.save(sgOperationRecords);
        }
        return Result.ok("撤销成功！");
    }

    /**
     * 根据机构获取任务类型
     *
     * @param orgCode
     * @return
     */
    @GetMapping("/getItemListByOrgCode")
    public Result<List<SgItemType>> getItemListByOrgCode(String orgCode) {
        List<SgItemType> sgItemTypes = sgItemTypeService.list(new QueryWrapper<SgItemType>().eq("sys_org_code", orgCode));
        return Result.ok(sgItemTypes);
    }
}
